package cc.rengu.igas.share.common.util;


import cc.rengu.igas.share.common.constant.ShareParamConstant;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;


/**
 * 用户服务器端对客户端提交的加密数据使用私钥进行解密 公钥加密--客户端 私钥解密--服务端
 *
 * @author fuyp
 */
public class RSACerPlus {
    // 私钥
    PrivateKey pk2;
    RSAPrivateKey rsaPriKey;
    RSAPublicKey rsaPubKey;

    /**
     * 初始化加载cer证书
     *
     * @throws Exception
     */
    public void initCer(String rootPath, String keystoreFilePath, String storepass, String keypass, String keyalias) throws Exception {
        String filePath = rootPath.concat(keystoreFilePath);
        File file = new File(filePath);
        FileInputStream fis2 = null;
        try {
            fis2 = new FileInputStream(file);
            // 加载证书库
            KeyStore ks = KeyStore.getInstance("JKS");
            // 证书库密码
            char[] kspwd = storepass.toCharArray();
            // 证书密码
            char[] keypwd = keypass.toCharArray();
            // 加载证书
            ks.load(fis2, kspwd);
            rsaPriKey = (RSAPrivateKey) ks.getKey(keyalias, keypwd);
            // 获取证书私钥
            pk2 = (PrivateKey) ks.getKey(keyalias, keypwd);
            Certificate cert = ks.getCertificate(keyalias);
            rsaPubKey = (RSAPublicKey) cert.getPublicKey();
            fis2.close();
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != fis2) {
                fis2.close();
            }
        }
    }

    /**
     * 解密字符串
     *
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    public String doDecrypt(String str) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        byte[] msg = Base64Converter.decode(str.getBytes("UTF-8"));
        StringBuffer sb = new StringBuffer();
        // 获取密码器实例
        Cipher cipher = Cipher.getInstance(ShareParamConstant.RSA_ALGORITHM);
        // 解密模式
        cipher.init(Cipher.DECRYPT_MODE, pk2);
        for (int i = 0; i < msg.length; i += 128) {
            byte[] doFinal;
            doFinal = cipher.doFinal(subarray(msg, i, i + 128));
            sb.append(new String(doFinal, "UTF-8"));
        }
        return sb.toString();
    }

    /**
     * 个人网银和直销银行渠道
     *
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     */
    /*USED*/
    public String doDecryptNormally(String str) throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
        byte[] msg = Base64Converter.decode(str.getBytes("UTF-8"));
        StringBuffer sb = new StringBuffer();
        // 获取密码器实例
        Cipher cipher = Cipher.getInstance(ShareParamConstant.RSA_ALGORITHM);
        // 解密模式
        cipher.init(Cipher.DECRYPT_MODE, pk2);
        sb.append(new String(cipher.doFinal(msg), "UTF-8"));
        return sb.toString();
    }

    /**
     * AES解密
     *
     * @param sSrc 待解密字符串
     * @param key  密钥串
     * @return
     * @throws Exception
     */
    public static String decrypt(String sSrc, String key) throws Exception {
        try {
            byte[] raw = key.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(2, skeySpec);
            byte[] encrypted1 = Base64Converter.decode(sSrc.getBytes("UTF-8"));
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(Base64Converter.decode(original), "UTF-8");
            ;
            return originalString;
        } catch (Exception ex) {

        }
        return null;
    }

    /**
     * 截取数组
     *
     * @param array
     * @param startIndexInclusive
     * @param endIndexExclusive
     * @return
     */
    public static byte[] subarray(byte[] array, int startIndexInclusive, int endIndexExclusive) {
        if (array == null) {
            return null;
        }
        if (startIndexInclusive < 0) {
            startIndexInclusive = 0;
        }
        if (endIndexExclusive > array.length) {
            endIndexExclusive = array.length;
        }
        int newSize = endIndexExclusive - startIndexInclusive;
        if (newSize <= 0) {
            return new byte[0];
        }
        byte[] subarray = new byte[newSize];
        System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
        return subarray;
    }
}

